from urllib.request import urlopen
from urllib.request import Request
import json
import time
import hmac
import hashlib
import base64
from urllib.parse import quote

def send_message(message: str):
    timestamp = int(round(time.time() * 1000))
    secret = 'SEC140512270eef348b8a952d0f50f762fc4f3921fb8f781424b966594a44157ac0'
    secret_enc = secret.encode('utf-8')
    string_to_sign = '{}\n{}'.format(timestamp, secret)
    string_to_sign_enc = string_to_sign.encode('utf-8')
    hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
    sign = quote(base64.b64encode(hmac_code))
    print(timestamp)
    print(sign)
    url = 'https://oapi.dingtalk.com/robot/send?access_token=3315d579c4876fa2d81a8acda6d7b7b273d4bb2f3650d3dfb002ad325a50014b&timestamp={}&sign={}'.format(timestamp,sign)
    headers = {
        'Content-Type': 'application/json;charset=utf-8'
    }
    data = {
        "msgtype": "text",
        "text": {
            "content": message
        }
    }
    data = json.dumps(data).encode('utf-8')
    request = Request(url, data=data, headers=headers)
    html = urlopen(request)
    result = json.loads(html.read().decode('utf-8'), encoding='utf-8')
    print(result)
    if result['errcode'] == 0:
        print('消息发送成功！')
        return True
    else:
        print('消息发送失败')
        return False

if __name__ == '__main__':
    send_message('安全签名测试')
